Comparison Operators

In R we can use comparison operators to compare variables and return logical values. Let's see some relatively self-explanatory examples:

Greater Than

In [3]:
5 > 6
Out[3]:
FALSE
In [7]:
6 > 5
Out[7]:
TRUE

We can also do element by element comparisons for two vectors:

In [5]:
v1 <- c(1,2,3)
v2 <- c(10,20,30)
In [6]:
v1 < v2
Out[6]:
  1. TRUE
  2. TRUE
  3. TRUE

Greater Than or Equal to

In [8]:
6 >= 6
Out[8]:
TRUE
In [10]:
6 >= 5
Out[10]:
TRUE
In [11]:
6 >= 7
Out[11]:
FALSE

Less Than and Less than or Equal To

In [12]:
3 < 2
Out[12]:
FALSE
In [13]:
2 <= 2
Out[13]:
TRUE

Be very careful with comparison operators and negative numbers! Use spacing to keep things clear. An example of a dangerous situation:

In [14]:
var <- 1
In [15]:
var
Out[15]:
1
In [16]:
# Comparing var less than negative 2
var < -2
Out[16]:
FALSE
In [17]:
# Accidentally reassigning var!
var <- 2
In [18]:
var
Out[18]:
2

Keep syntax highlighting in mind to help you avoid this mistake!

Not Equal

In [19]:
5 != 2
Out[19]:
TRUE
In [26]:
5 != 5
Out[26]:
FALSE

Equal

In [27]:
5 == 5
Out[27]:
TRUE
In [28]:
2 == 3
Out[28]:
FALSE

Vector Comparisons

We can apply a comparison of a single number to an entire vector, for example:

In [29]:
v <- c(1,2,3,4,5)
In [30]:
v < 2
Out[30]:
  1. TRUE
  2. FALSE
  3. FALSE
  4. FALSE
  5. FALSE
In [31]:
v == 3
Out[31]:
  1. FALSE
  2. FALSE
  3. TRUE
  4. FALSE
  5. FALSE

Later on we will see how we can use these vector comparisons to select parts of a vector!